package com.cq.androidtools.flow

import androidx.lifecycle.lifecycleScope
import com.cq.androidtools.databinding.ActivityFlowBinding
import com.cq.androidtools.jetpack.databinding.DataBindingActivity
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * 作者: CQ
 * 日期: 2022-06-10
 * 说明:
 */
class FlowActivity : DataBindingActivity<ActivityFlowBinding>() {
    private val _stateFlow = MutableStateFlow(-1)
    private val stateFlow = _stateFlow.asStateFlow()

    override fun ActivityFlowBinding.initBinding() {
        lifecycleScope.launch {
            sharedFlow.collect {
                println("sharedFlow = $it")
            }

        }
        lifecycleScope.launch {
            stateFlow.collect {
                println("stateFlow = $it")
            }
        }


        stateFlow1.setOnClickListener {
            stateFlow11()
        }
        shareFlow1.setOnClickListener {
            count1()
        }
    }


    private fun stateFlow11() {
        lifecycleScope.launch {
            _stateFlow.value = ++count
            if (count / 2 == 0) {
                _stateFlow.value = count
            }
        }
    }

    private fun count1() {
        lifecycleScope.launch {
            _sharedFlow.emit(++count)
            if (count % 2 == 0) {
                _sharedFlow.emit(count)
            }
        }
    }

    private val _sharedFlow = MutableSharedFlow<Int>()
    val sharedFlow = _sharedFlow.asSharedFlow()
    var count = 0
}